<template>
  <div class="article-meta">
    <nuxt-link :to="`/profile/${article.author.username}`">
      <user-image :src="article.author.image" />
    </nuxt-link>
    <div class="info">
      <nuxt-link
        :to="`/profile/${article.author.username}`"
        class="author"
      >{{article.author.username}}</nuxt-link>
      <span class="date">{{article.createdAt | format('MMMM DD, YYYY')}}</span>
    </div>
    <button
      class="btn btn-sm btn-outline-secondary"
      @click="triggerFollow"
      :style="{disabled: isUpdateFollowing}"
    >
      <i class="ion-plus-round"></i>
      &nbsp;
      {{article.following ? `Unfollow ${article.author.username}` : `follow ${article.author.username}`}}
      <span
        class="counter"
      ></span>
    </button>
    &nbsp;&nbsp;
    <button
      class="btn btn-sm btn-outline-primary"
      @click="triggerFavorited"
      :style="{disabled: isUpdateFavorited}"
    >
      <i class="ion-heart"></i>
      &nbsp;
      {{article.favorited ? 'Unfavorite Article' : 'Favorite Article'}}
      <span
        class="counter"
      >({{article.favoritesCount}})</span>
    </button>
  </div>
</template>

<script>
import { favoriteArticle, unfavoriteArticle } from '@/api/article.js'
import { followUser, unfollowUser } from '@/api/profile.js'
import UserImage from '@/pages/components/userImage.vue'
import { mapState } from 'vuex'
export default {
  name: 'ArticleMeta',
  components: { UserImage },
  props: {
    article: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      isUpdateFollowing: false,
      isUpdateFavorited: false,
    }
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    async triggerFollow() {
      if (!this.user) {
        this.$router.push({
          name: 'login',
        })
        return
      }
      this.isUpdateFollowing = true
      const { username, following } = this.article.author
      const request = following ? followUser : unfollowUser
      const { data } = await request(username)
      if (data && data.profile) {
        this.article.author.following = data.profile.following
      }
      this.isUpdateFollowing = false
    },
    async triggerFavorited() {
      if (!this.user) {
        this.$router.push({
          name: 'login',
        })
        return
      }
      this.isUpdateFavorited = true
      const { slug, favorited } = this.article
      const request = favorited ? unfavoriteArticle : favoriteArticle
      const { data } = await request(slug)
      if (data && data.article) {
        this.article.favorited = data.article.favorited
        this.article.favoritesCount = data.article.favoritesCount
      }
      this.isUpdateFavorited = false
    },
  },
}
</script>